package com.linln.modules.member.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.linln.common.data.PageSort;
import com.linln.common.utils.MoneyUtils;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberAgentMoneyChange;
import com.linln.modules.member.domain.MemberOrder;
import com.linln.modules.member.repository.MemberAgentMoneyChangeRepository;
import com.linln.modules.member.repository.MemberAgentRepository;
import com.linln.modules.member.repository.MemberOrderRepository;
import com.linln.modules.member.service.MemberOrderService;

/**
 * @author hct
 * @date 2019/09/12
 */
@Service
public class MemberOrderServiceImpl implements MemberOrderService {

    @Autowired
    private MemberOrderRepository memberOrderRepository;
    @Autowired
    private MemberAgentRepository memberAgentService;

    @Autowired
    private MemberAgentMoneyChangeRepository changeRepository;

    /**
     * 根据ID查询数据
     * @param id 主键ID
     */
    @Override
    @Transactional
    public MemberOrder getById(Long id) {
        return memberOrderRepository.findById(id).orElse(null);
    }
   
   @Override
    public   Boolean delCollect(Long id){
	   boolean isOk=false;
	   try{
		   memberOrderRepository.deleteById(id);
        isOk=true;
	   }catch(Exception e){
		   
	   }
       return isOk;
   }
   @Override
   public Double getSumByArea(String area) {
	  return memberOrderRepository.getSumByArea(area);
   }
   
   public Double getSumByAreaAndToday(String area) {
		  return memberOrderRepository.getSumByAreaAndToday(area);

   }

   @Override
   public Double getSumByArea() {
	  return memberOrderRepository.getSumByArea();
   }
   @Override
   public Double getSumByArea(int type) {
		  return memberOrderRepository.getSumByArea(type);
   }

    /**
     * 获取分页列表数据
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<MemberOrder> getPageList(Example<MemberOrder> example,Integer pageNumber,Integer pageSize) {
        // 创建分页对象
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        PageRequest page = PageSort.pageRequest(pageNumber,pageSize,sort);
        return memberOrderRepository.findAll(example, page);
    }

    @Override
    public Page<MemberOrder> getPageList(Example<MemberOrder> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return memberOrderRepository.findAll(example, page);
    }
    
    

    /**
     * 保存数据
     * @param MemberZan 实体对象
     */
    @Override
    public MemberOrder save(MemberOrder MemberZan) {
        return memberOrderRepository.save(MemberZan);
    }
 
    public  MemberOrder findByOrderCode(String orderCode) {
        return memberOrderRepository.findByOrderCode(orderCode);

    }
    
    public Integer updatePayStatus( String orderCode) {
        return memberOrderRepository.updatePayStatus(orderCode);

    }
    public Integer updateRefundStatus( String orderCode) {
    	try {
    		MemberOrder order=memberOrderRepository.findByOrderCode(orderCode);
       		MemberAgentMoneyChange change=new MemberAgentMoneyChange();
       		MemberAgent agent=memberAgentService.getByMemberIdAndArea(order.getMember().getId(),order.getArea());
       		change.setArea(order.getArea());
       		change.setChangemoney(order.getMoney());
       		change.setPreMoney(agent.getCurmoney());
       		//退钱给用户的时候 减少代理商的金额
       		change.setLastmoney(MoneyUtils.sub(agent.getCurmoney(),order.getMoney()));
       		change.setCreateDate(order.getCreateDate());
       		change.setUpdateDate(order.getCreateDate());
       		change.setStatetype(2);
       		change.setStatus(1);           	        		
       		changeRepository.save(change);
       		System.out.println("添加退款详情记录"); 

       		}catch(Exception e) {
	        		System.out.println("添加详情记录异常"); 
       		}
    	
        return memberOrderRepository.updateRefundStatus(orderCode);

    }

    @Override
    public Long countOrder(Example<MemberOrder> example) {
        return memberOrderRepository.count(example);
    }

    
    
   	public Page<MemberOrder> getPageList(String area,Integer payStatus){
       	  // 创建分页对象
           PageRequest page = PageSort.pageRequest(Sort.Direction.ASC);

           // 使用Specification复杂查询
           return memberOrderRepository.findAll(new Specification<MemberOrder>(){

               @Override
               public Predicate toPredicate(Root<MemberOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                   List<Predicate> preList = new ArrayList<>();
                   preList.add(cb.equal(root.get("area").as(Integer.class), area));
                   if(payStatus!=null && payStatus.intValue()>0) {
                   preList.add(cb.equal(root.get("payStatus").as(Integer.class), payStatus));
                   }
                   In<Integer> in = cb.in(root.get("type"));
  			        in.value(1);
  			        in.value(2);
  			        in.value(3);
  			        in.value(4);
  			        preList.add(in);
                   Predicate[] pres = new Predicate[preList.size()];
                   return query.where(preList.toArray(pres)).getRestriction();
               }

           }, page);
       }
}